package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.threadlocal.AppThreadLocalUtils;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserServiceImpl apUserService;

    @Override
    public ResponseResult login(LoginDTO dto) {
        //判断是否有设备id
        if(dto.getEquipmentId() == null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "设备Id为空");
        }
        //1.检查参数 判断手机号密码是否为空
        if (StringUtils.isNotEmpty(dto.getPhone())){
            //判断密码是否为空
            if (StringUtils.isEmpty(dto.getPassword())){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"密码不能为空");
            }
            //判断当前用户是否存在
            ApUser apUser = apUserService.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser == null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该用户不存在");
            }
            //校验密码是否正确
            String inputpwd = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
//            if (!inputpwd.equals(apUser.getPassword())){
//                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
//            }
            //颁发token
            Map<String, Object> map = new HashMap<>();
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
            map.put("user", apUser);
            return ResponseResult.okResult(map);
        }else {

            Map<String,Object> map = new HashMap<>();
            // 通过设备ID登录的 userId存0
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}
